#include <cstdio>
#include <cstring>
#include <cstdlib>
#include "lib.h"
using namespace std;

const int _buf_size = 1000000;

int main(int argc, char *argv[])
{
	if (argc != 5 && argc != 6) {
		printf("%s: not enough parameters!\n", argv[0]);
		exit(1);
	}
	int ind = s_to_i(argv[4], -1);
	if (ind < 0) {
		printf("%s: error format of parameter 4!\n", argv[0]);
		exit(1);
	}
	int par = -1;
	if (argc == 6) par = s_to_i(argv[5]);

	FILE *f1 = fopen(argv[1], "r");
	FILE *f2 = fopen(argv[2], "w");
	FILE *f3 = NULL;
	bool flag = true;
	if (strcmp(argv[3], "NULL") !=0) {
		f3 = fopen(argv[3], "w");
		flag = (f3 != NULL);
	}
	if (f1 == NULL || f2 == NULL || !flag) {
		printf("%s: cannot open file(s)!\n", argv[0]);
		exit(2);
	}
	setvbuf(f1, NULL, _IOFBF, _buf_size);
	setvbuf(f2, NULL, _IOFBF, _buf_size);
	setvbuf(f3, NULL, _IOFBF, _buf_size);

	int c1 = 0, c2 = 0;
	while (1) {
		char c = fgetc(f1);
		if (c == EOF) break;
		if (c1 < ind) {
			fputc(c, f2);
			if (c == '\n') ++c1;
		} else {
			if (c == '\r' && c2 == 0)
				fputc(c, f2);
			else {
				if (f3 == NULL)
					break;
				fputc(c, f3);
			}
			if (c == '\n') ++c2;
		}
		if (c == '\n' && (c1 + c2 + 1) % par == 0)
			printf("finished %d lines.\n", c1 + c2);
	}

	fclose(f1);
	fclose(f2);
	fclose(f3);

	printf("%s: done.\n", argv[0]);

	return 0;
}

